#include "Server.h"

using namespace std;
using namespace net;
/**
 * Server::Server(int maxNodes)
 *
 * Description
 *     Starts the server by initializing all the necessary sockets,
 *     initializing the mesh, then going into a continues loop where
 *     it gets and sends packets from two nodes.
 *
 * Parameters
 *     int maxNodes - the maximum number of nodes or clients that can connect
 */
Server::Server(int maxNodes){
    cout << "Initializing Server.\n";
    if (!InitializeSockets())
        throw "failed to initialize sockets";

    mesh = new Mesh(PROTOCOLID, maxNodes, SENDRATE, TIMEOUT);
    if (!(*mesh).Start(MESHPORT))
        throw "failed to start mesh on port " + MESHPORT; // error handling for mesh

    node = new Node(PROTOCOLID, SENDRATE, TIMEOUT);
    if (!(*node).Start(NODEPORT))
        throw "failed to start node on port " + NODEPORT; // error handling for node

    (*mesh).Reserve(0, Address(127,0,0,1,NODEPORT)); //reserved server address
    (*node).Join(Address(127,0,0,1,MESHPORT)); 

    while (true){//get send loop...
        unsigned char packet[256]; // buffer packet
        unsigned char n1packet[256]; // node 1s packet
        unsigned char n2packet[256]; // node 2s packet
        if ((*node).IsConnected()) {
            assert((*node).GetLocalNodeId() == 0);
            while (true) {
                int nodeId = -1;
                int bytes_read = (*node).ReceivePacket(nodeId, packet, 256); // receive this 
                if (bytes_read == 0) // receiving done
                    break;
                assert(nodeId > 0);
                cout << "node[" << nodeId << "] says [" << packet << "]\n";
                if(nodeId == 1) // copys packet from buffer into node 1 packet
                    for(int i = 0; i < 256; i++){
                        n1packet[i] = packet[i];
                        if(packet[i] == 0)
                            break;
                    }
                if(nodeId == 2) // copys packet from buffer into node 2 packet
                    for(int i = 0; i < 256; i++){
                        n2packet[i] = packet[i];
                        if(packet[i] == 0)
                            break;
                    }

                for (int i = 1; i < (*node).GetMaxAllowedNodes(); ++i)
                    if ((*node).IsNodeConnected(i)) {
                        if(i == 1) // send packets to appropriate node
                            (*node).SendPacket(i, n2packet, 256);
                        if(i == 2)
                            (*node).SendPacket(i, n1packet, 256);
                    }
            }
        }
        (*node).Update(DELTATIME);
        (*mesh).Update(DELTATIME);
        wait_seconds(DELTATIME); //let server think, don't delete this line..
    }
    (*mesh).Stop();	
    ShutdownSockets();
}
